import qs from 'query-string';
import env from '@gis/lib/env.js';
import md5 from '@gis/lib/plugins/spark-md5.js';
import styleSheets from '@gis/lib/utils/styleSheets.js';
import loadScript from '@gis/lib/utils/loadScript.js';

export function isUseOfflineMap() {
  /* 这个方法调用必须在 map load 之后 */
  return window.__USE_OFFLINE_BMAP === true;
}
export async function mapLoader(url) {
  return await new Promise((resolve, reject) => {
    let script = document.querySelector('script[src="' + url + '"]');
    if (!script) {
      script = document.createElement('script');
    }
    if (script.getAttribute('data-ready') === 'true') {
      return resolve();
    }
    let id = '_map_' + md5.hash(url);
    let originOnLoad = window[id];
    window[id] = function () {
      script.setAttribute('data-ready', 'true');
      typeof originOnLoad === 'function' && originOnLoad();
      delete window[id];
      resolve();
      originOnLoad = resolve = script = url = id = null;
    };
    url = url.replace(/&?callback=[^&]*/g, '') + '&callback=' + id;
    script.charset = 'utf-8';
    script.src = url.replace(/\?&/g, '?').replace(/&+/g, '&').replace(/&$/, '');
    script.onerror = () => reject();
    document.head.appendChild(script);
  });
}
export async function loadOnlineBMap(params) {
  params = Object.assign({}, params);
  let query = {
    v: params.version || '1.0',
    ak: params.key || 'rqMCPW9Ua1293iynKdb2lnrDWGh9zB6U',
    type: params.type || 'webgl',
  };
  let url = 'https://api.map.baidu.com/api?' + qs.stringify(query);
  await mapLoader(url);
  window.BMap = window.BMap || window.BMapGL;
}
export async function loadOfflineBMap(params) {
  params = Object.assign({}, params);
  let mapStyle = params.mapStyle || 'mapstyle';
  let url = params.mapServerUrl || env.get('VUE_APP_MAP_AGENT_URL') || 'https://m.xinwangzn.com:8081';
  let mapAgentUrl = url.replace(/[\/\\]+$/, '');

  let MAP_HOME_ORIGIN = mapAgentUrl + '/';
  let MAP_HOME_DIR = 'bmap/offlinemap/';
  let MAP_HOME_PATH = MAP_HOME_ORIGIN + MAP_HOME_DIR;

  /* 地图主题样式地址,MAP_STYLE_JSON,MAP_STYLE_JSON_WEB_SIDE需要同步修改 */
  let MAP_STYLE_JSON = MAP_HOME_PATH + 'customstyle/' + mapStyle;
  let MAP_STYLE_JSON_WEB_SIDE = MAP_HOME_PATH + 'customstyle/webside/' + mapStyle + '.json';
  window.offmapcfg = Object.assign(
    {
      home: MAP_HOME_PATH, //地图API主目录
      imgext: '.jpg', //图片格式------ 根据需要修改，一般是 .png .jpg
      customstyle: MAP_STYLE_JSON, //自定义样式的地址，为空默认在 offlinemap/customstyle/mapstyle 文件
      websidestyle: MAP_STYLE_JSON_WEB_SIDE, //自定义样式的地址，浏览器端 setMapStyleV2 使用的
      tiles_dir: '', //图片瓦片图的地址，为空默认在 offlinemap/tiles/ 目录
      tiles_v_dir: mapAgentUrl + '/bmap/offlinemap/tiles', //矢量瓦片图的地址，为空默认在 offlinemap/tiles_v/ 目录
      tiles_satellite_dir: '', //卫星图的地址，为空默认在 offlinemap/tiles_satellite/ 目录
      tiles_road_dir: '', //图片路网的地址，为空默认在 offlinemap/tiles_road/ 目录
      tiles_v_road_dir: '', //矢量路网的地址，为空默认在 offlinemap/tiles_v_road/ 目录
    },
    params
  );
  window.BMap_loadScriptTime = new Date().getTime();
  styleSheets.addLink(MAP_HOME_PATH + 'css/bmap.css');
  //加载地图API主文件
  await loadScript(MAP_HOME_PATH + 'bmapgl.min.js');
  await loadScript(MAP_HOME_PATH + 'mapvgl.min.js');
  window.BMap = window.BMap || window.BMapGL;
  window.__USE_OFFLINE_BMAP = true;
}
export async function loadBMap(params) {
  params = Object.assign({}, params);
  if (params.useOnline === true) {
    return await loadOnlineBMap(params);
  }
  if (params.useOffline === true) {
    return await loadOfflineBMap(params);
  }
  try {
    await loadOnlineBMap(params);
  } catch (e) {
    await loadOfflineBMap(params);
  }
}
export async function loadAMap(params) {
  params = Object.assign({}, params);
  let query = {
    v: params.version || '1.4.15',
    key: params.key || 'd99cf0fc41f79425572e5b1298c0f21c',
  };
  let url = 'https://webapi.amap.com/maps?' + qs.stringify(query);
  await mapLoader(url);
}
